package com.qf.java2201.web;

import com.fasterxml.jackson.databind.util.BeanUtil;
import com.qf.java2201.pojo.HUser;
import com.qf.java2201.pojo.HUserinfo;
import com.qf.java2201.service.UserService;
import com.qf.java2201.service.impl.UserServiceImpl;
import com.qf.java2201.utils.MD5Util;
import lombok.SneakyThrows;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/register")
public class RegServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String uname = req.getParameter("uname");
        //String upwd = req.getParameter("upwd");
        //String grpwd = req.getParameter("grpwd");
        //String drealname = req.getParameter("drealname");
        //String dsex = req.getParameter("dsex");
        //String dage = req.getParameter("dage");
        //String dphone = req.getParameter("dphone");
        //String didcard = req.getParameter("didcard");
        //String demail = req.getParameter("demail");
        //String dqq = req.getParameter("dqq");

        //自动封装 表单数据 以表单项 name 为key  表单输入的值为 value

        Map<String, String[]> parameterMap = req.getParameterMap();

        HUserinfo hUserinfo = new HUserinfo();
        HUser hUser = new HUser();

        //借助工具 自动吧map中的数据  封装到 javabean 中  这个是根据属性名来封装的
        //所以 map  中的  key  必须 和javabean 中的 属性名一致

        BeanUtils.populate(hUser, parameterMap);
        BeanUtils.populate(hUserinfo, parameterMap);

        hUser.setUi(hUserinfo);
        //工具类 对 明文密码进行加密  数据库存的是 加密后的密码

        String s = MD5Util.encodePwdByMD5(hUser.getUpwd());
        hUser.setUpwd(s);

        UserService userService = new UserServiceImpl();

        int result = userService.register(hUser);

        if (result == 1) {
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        } else {
            //注册失败  跳转到注册页面
            req.setAttribute("reg_info","注册失败");

            req.getRequestDispatcher("/req.jsp").forward(req, resp);
        }

    }
}

